<?php

namespace app\common\business;
use app\common\model\mysql\Category as CategoryModel;
use think\facade\Log;

class Category {

    public function __construct() {
        $this->model = new CategoryModel();
    }

    public function getLists($data, $num) {

        $list = $this->model->getLists($data, $num);
        if (!$list) {
            return [];
        }

        $result           = $list->toArray();
        $result['render'] = $list->render();

        /***以下为带领同学们解读代码***/
        // 思路： 第一步拿到列表中id 第二步：in mysql 求count  第三步：把count填充到列表页中
        $pids = array_column($result['data'], "id");
        if ($pids) {
            $idCountResult = $this->model->getChildCountInPids(['pid' => $pids]);
            $idCountResult = $idCountResult->toArray(); //  如果没有的话会返回空数组

            $idCounts = [];
            // 第一种方式
            foreach ($idCountResult as $countResult) {
                $idCounts[$countResult['pid']] = $countResult['count'];
            }
        }
        if ($result['data']) {
            foreach ($result['data'] as $k => $value) {
                /// $a ?? 0 等同于 isset($a) ? $a : 0。
                $result['data'][$k]['childCount'] = $idCounts[$value['id']] ?? 0;
            }
        }

        /****解读end*****/

        return $result;

    }

    public function getNormalAllCategorys() {
        $field     = "id as category_id, name, pid";
        $categorys = $this->model->getNormalCategorys($field);
        if (!$categorys) {
            return $categorys;
        }
        $categorys = $categorys->toArray();
        return $categorys;
    }

    public function getNormalCategorys() {
        $field     = "id, name, pid";
        $categorys = $this->model->getNormalCategorys($field);
        if (!$categorys) {
            return $categorys;
        }
        $categorys = $categorys->toArray();
        return $categorys;
    }

    public function add($data) {
        //设置 status 为正常的状态
        $data['status'] = config("status.mysql.table_normal");
        //获取需要添加的分类信息
        $name = $data['name'];

        $name = $this->model->where('name', $name)->findOrEmpty();
        if (!$name->isEmpty()) {
            return 0;
        }
        try {
            $this->model->save($data);
        } catch (\Exception $e) {
            throw new \think\Exception("服务内部异常");
        }
        return $this->model->id;
    }

    /**
     * 获取一级分类的内容 代码提供好的 带同学们解读下 @9-5
     * @return array
     */
    public function getNormalByPid($pid = 0, $field = "id, name, pid") {
        //$field = "id,name,pid";
        try {
            $res = $this->model->getNormalByPid($pid, $field);
        } catch (\Exception $e) {
            // 记得记录日志。
            return [];
        }
        $res = $res->toArray();

        return $res;
    }

}